package at.fhj.itm11.forum.data;

import java.util.List;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import at.fhj.itm11.forum.model.Comment;

@ApplicationScoped
public class CommentRepository {
	
	@Inject
	private EntityManager em;
	
	public Comment findCommentById(Long id) {
		return em.find(Comment.class, id);
	}
	
	public List<Comment> findCommentsByPostOrderedByDate(long postId) {
		CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Comment> criteria = cb.createQuery(Comment.class);
        Root<Comment> comment = criteria.from(Comment.class);
        
        criteria.select(comment).where(cb.equal(comment.get("post"), postId));
        criteria.orderBy(cb.asc(comment.get("date")));
        return em.createQuery(criteria).getResultList();
       
		
	}
	
}
